<template>
  <div class="departments">
    <!-- 卡片 -->
    <el-card>
      <!-- tabs -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="组织架构" name="first">
          <!-- layout 栅格(shan ge)布局 -->
          <el-row type="flex" justify="space-between">
            <el-col :span="6">
              <h4>江苏传智播客教育科技股份有限公司</h4>
            </el-col>
            <el-col class="right-col" :span="6">
              <span class="leader">负责人</span>
              <!-- 下拉菜单 -->
              <el-dropdown>
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item>
                    <el-button
                      type="text"
                      @click="dialogFormVisible = true"
                    >添加子部门</el-button>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>
          <!-- 和底部的内容分割开来 -->
          <el-divider />

          <!-- tree架构 -->
          <el-tree
            :data="departs"
            :props="defaultProps"
            @node-click="handleNodeClick"
          >
            <!-- 通过插槽传递自定义的结构 -->
            <template #default="{ data }">
              <el-row class="tree-row" type="flex" justify="space-between">
                <el-col :span="6"> {{ data.name }}</el-col>
                <el-col class="right-col" :span="6">
                  <span class="leader">{{ data.manager }}</span>
                  <!-- 下拉菜单 -->
                  <el-dropdown>
                    <span class="el-dropdown-link">
                      操作<i class="el-icon-arrow-down el-icon--right" />
                    </span>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item>
                        <el-button
                          type="text"
                          @click="addChildren(data)"
                        >添加子部门</el-button>
                      </el-dropdown-item>
                      <el-dropdown-item>
                        <el-button
                          type="text"
                          @click="enterEdit(data)"
                        >查看部门</el-button>
                      </el-dropdown-item>
                      <el-dropdown-item>
                        <el-button
                          type="text"
                          @click="delById(data)"
                        >删除部门</el-button>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </el-col>
              </el-row>
            </template>
          </el-tree>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 弹框 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogFormVisible"
      @closed="onClosed"
    >
      <el-form ref="form" :rules="rules" :model="form">
        <el-form-item
          label="部门名称"
          :label-width="formLabelWidth"
          prop="name"
        >
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="部门编码"
          :label-width="formLabelWidth"
          prop="code"
        >
          <el-input v-model="form.code" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="部门负责人"
          :label-width="formLabelWidth"
          prop="manager"
        >
          <!-- 通过输入框的焦点设置绑定事件，获取负责人的数据，并渲染到结构 -->
          <el-select
            v-model="form.manager"
            placeholder="请选择"
            @focus="getFocus"
          >
            <el-option
              v-for="item in managers"
              :key="item.id"
              :label="item.username"
              :value="item.username"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="部门介绍"
          :label-width="formLabelWidth"
          prop="introduce"
        >
          <el-input v-model="form.introduce" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="onCancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 删除弹框 -->
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="delById"
    >
      <span>这是一段信息</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="dialogVisible = false"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getDepartments,
  addDepartments,
  getDepartmentById,
  editDepartment,
  delDepartmentById
} from '@/api/departments'
import { getEmployeeSimple } from '@/api/employees'
export default {
  name: 'Departments',
  data() {
    return {
      activeName: 'first',
      // tree的对应关系
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 测试的数据
      departs: [
        {
          name: '总裁办',
          manager: '曹操',
          children: [{ name: '董事会', manager: '曹丕' }]
        },
        { name: '行政部', manager: '刘备' },
        { name: '人事部', manager: '孙权' }
      ],

      // 弹出框的数据
      dialogFormVisible: false, // 是否显示弹框
      form: {
        name: '', // 部门名称
        instroduce: '', // 部门介绍
        manager: '', // 部门负责人
        pid: '', // 父级部门id
        code: '' // 部门编码
      },
      formLabelWidth: '120px',
      // 部门负责人的数组
      managers: [],

      // 表单校验
      rules: {
        name: [
          { required: true, message: '不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '请输入1-50个字符', trigger: 'change' }
        ], // 部门名称
        code: [
          { required: true, message: '不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '请输入1-50个字符', trigger: 'change' }
        ],
        manager: [{ required: true, message: '不能为空', trigger: 'blur' }],
        // 部门负责人
        introduce: [
          { required: true, message: '不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '请输入1-300个字符', trigger: 'change' }
        ] // 部门介绍
      },
      // 是否显示删除弹框
      dialogVisible: false
    }
  },
  computed: {
    title() {
      return this.form.id ? '编辑' : '新增'
    }
  },
  created() {
    // 声明周期钩子里调用获取tree数据的方法
    this.getData()
  },
  methods: {
    onClosed() {},
    // 添加删除功能
    delById(data) {
      this.$confirm('确认删除？')
        .then(async(res) => {
          await delDepartmentById(data.id)
          this.getData()
        })
        .catch((res) => {})
    },

    // 添加子节点
    addChildren(data) {
      // 把id赋值给pid
      this.form.pid = data.id
      // 弹框
      this.dialogFormVisible = true
    },

    // 清空表单
    onCancel() {
      // 注意：
      // 如果修改了form中数据的指向（重新赋值）会出现无法清空的问题
      // 因此要自己清空
      this.form = {
        name: '', // 部门名称
        instroduce: '', // 部门介绍
        manager: '', // 部门负责人
        pid: '', // 父级部门id
        code: '' // 部门编码
      }
      this.dialogFormVisible = false
    },
    // 进入编辑页面
    async enterEdit(data) {
      const res = await getDepartmentById(data.id)
      // 表单重新赋值
      this.form = { ...res }
      // 弹出弹框
      this.dialogFormVisible = true
    },
    // 获取tree数据的方法（抽取方法）
    async getData() {
      // 获取请求数据
      const res = await getDepartments()
      // console.log(res)
      // 排除掉pid为-1的选项
      const res1 = res.depts.filter((v) => v.pid !== '-1')
      // console.log(res1)
      // 找到顶级节点
      const root = res1.filter((v) => v.pid === '')
      // console.log(root)
      // 找后代
      root.forEach((v) => {
        // 获取子节点
        // pid和当前节点的id相同
        v.children = res1.filter((vc) => vc.pid === v.id)
        // 把处理完毕的数据  设置上去
        this.departs = root
      })
    },
    // 提交表单
    submitForm() {
      this.$refs.form.validate(async(valid) => {
        if (valid) {
          if (this.form.id) {
            await editDepartment(this.form)
            // console.log(res)
          } else {
            //  调用接口
            await addDepartments(this.form)
            // console.log(res)
          }
          // 成功弹出框提示
          this.$message.success(`${this.title}成功`)
          // 调用清除表单数据的逻辑
          this.onCancel()
          // 调用获取tree数据的方法
          this.getData()
        } else {
          // 数据有误弹出框提示
          this.$message.error('数据格式有误，请检查！')
          return false
        }
      })
    },
    // 获取部门负责人的信息
    async getFocus() {
      // 调用接口
      const res = await getEmployeeSimple()
      // console.log(res)
      this.managers = res
    },

    handleClick() {},

    handleNodeClick(data) {
      console.log(data)
    }
  }
}
</script>
<style lang="scss">
.departments {
  .el-tabs__content {
    padding: 40px;
    padding-top: 20px;
    h4 {
      margin: 0;
      font-size: 14px;
    }
    .right-col {
      text-align: right;
    }
    .leader {
      font-size: 14px;
      margin-right: 10px;
    }
    .el-tree-node__content {
      // width: 100%;
      // display: block;
      .tree-row {
        flex: 1;
      }
    }
  }
}
</style>
